<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class CouponDistribution extends Model
{
    use HasFactory;

    /**
     * 可批量赋值的属性
     */
    protected $fillable = [
        'coupon_id',
        'distribution_type',
        'target_users',
        'quantity',
        'distributed_quantity',
        'notes',
        'created_by',
    ];

    /**
     * 属性类型转换
     */
    protected $casts = [
        'target_users' => 'array',
        'quantity' => 'integer',
        'distributed_quantity' => 'integer',
    ];

    /**
     * 分发类型常量
     */
    const TYPE_MANUAL = 'manual';      // 手动发放
    const TYPE_AUTO = 'auto';          // 自动发放
    const TYPE_ACTIVITY = 'activity';  // 活动发放

    /**
     * 关联优惠券
     */
    public function coupon(): BelongsTo
    {
        return $this->belongsTo(Coupon::class);
    }

    /**
     * 关联创建人
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 访问器：类型文本
     */
    public function getTypeTextAttribute(): string
    {
        return match ($this->distribution_type) {
            self::TYPE_MANUAL => '手动发放',
            self::TYPE_AUTO => '自动发放',
            self::TYPE_ACTIVITY => '活动发放',
            default => '未知',
        };
    }

    /**
     * 增加已发放数量
     *
     * @param int $count
     */
    public function incrementDistributedQuantity(int $count = 1): void
    {
        $this->increment('distributed_quantity', $count);
    }
}
